package logic

import (
	"context"
	"errors"
	"video-guard/models/mysql"

	"video-guard/videorpc/internal/svc"
	"video-guard/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CollectionAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCollectionAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CollectionAddLogic {
	return &CollectionAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CollectionAddLogic) CollectionAdd(in *videorpc.CollectionAddRequest) (*videorpc.CollectionAddResponse, error) {
	// todo: add your logic here and delete this line

	var collection mysql.CollectionInfo

	err := collection.FindCollectionById(mysql.DB, in.UserId, in.VideoId)
	if err != nil {
		return nil, errors.New("查询失败")
	}

	if collection.ID != 0 {
		return nil, errors.New("用户已收藏该视频")
	}

	collection = mysql.CollectionInfo{
		UserId:  int(in.UserId),
		VideoId: int(in.VideoId),
	}

	err = collection.CollectionAdd(mysql.DB)
	if err != nil {
		return nil, errors.New("收藏失败")
	}

	var video mysql.VideoInfo

	err = video.FirstVideoById(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("该视频不存在")
	}

	video.CollectNum++

	err = video.CollectNumAdd(mysql.DB, in.VideoId)
	if err != nil {
		return nil, errors.New("收藏数添加失败")
	}

	return &videorpc.CollectionAddResponse{
		CollectionId: int64(collection.ID),
	}, nil
}
